﻿using Peninsula.Web.Infrastructure;
using Peninsula.Web.Models.Account;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Peninsula.Utility.Extensions;
using Peninsula.Utility.Helper;
using Peninsula.Site.Data.Result;

namespace Peninsula.Web.Controllers
{
    public class AccountController : HouseholdsBaseController
    {

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {

            SetPageTitle("Peninsula小区报修平台");
            return View(new LoginViewModel() { ReturnUrl = returnUrl });
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(LoginViewModel model)
        {

            bool isLockout = false;
            if (ModelState.IsValid && Householdsmanger.VaildateHouseholds(model.HouseholdsName, model.Password, out isLockout))
            {
                var households = Householdsmanger.Get(model.HouseholdsName);
                HouseholdsSignIn(new Models.Sessions.HouseholdsSession(households), model.RememberMe);
                if (model.ReturnUrl.IsNullOrWhiteSpace() || model.ReturnUrl.Equals("/"))
                {

                    return RedirectToRoute(RouteConfig.Default, new { controller = "Home", action = "Index" });
                }
                else
                {
                    return Redirect(model.ReturnUrl);
                }
            }
            if (isLockout)
            {
                ModelState.AddModelError("", "尝试错误过多，账户被锁定！");
            }
            else
            {
                ModelState.AddModelError("", "账户密码错误！");
            }

            return View(model);
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Logout()
        {
            base.HouseholdsSignOut();
            //return RedirectToAction("Login");
            return RedirectToAction("Index", "Home");

        }


        /// <summary>
        /// 个人中心
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult MyProfile() {
            DataAccess.POCO.Households Households = null;
            Households = HouseholdsSession.HouseholdsEntiy;
            SetPageTitle("个人中心");
            SetBreadcrumb(parentName: Households.TrueName, currentName: "个人中心");
            return View(Households);
        }

        /// <summary>
        /// 个人中心
        /// </summary>
        /// <param name="postHouseholds"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult MyProfile(Models.Account.ProfileModel postHouseholds) {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                if (postHouseholds.NewPassword.IsNullOrWhiteSpace())
                {
                    ModelState.Remove("Password");
                }
                if (ModelState.IsValid)
                {
                    var householdsEntiy = HouseholdsSession.HouseholdsEntiy;
                    ValueCopyHelper.CopyProperty(householdsEntiy, postHouseholds, false,
                        nameof(postHouseholds.TrueName),
                        nameof(postHouseholds.Sex),
                        nameof(postHouseholds.Email),
                        nameof(postHouseholds.Phone));

                    // 修改新密码
                    if (!Householdsmanger.SetIfChangePassword(householdsEntiy, postHouseholds.Password, postHouseholds.NewPassword))
                    {
                        result.Success = false;
                        result.AddMessage("密码错误！");
                    }
                    else
                    {
                        householdsEntiy.SetUpdateInfo(HouseholdsSession.HouseholdsEntiy.UserName);
                        Householdsmanger.Update(householdsEntiy);

                        result.Success = true;
                        result.RedirectUrl = Url.Action("Index","Home");
                        result.AddMessage("保存成功！");
                    }
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }
    }
}